/**
 * 屏幕适配 Composable
 */
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { getScreenInfo } from '../utils/platform'
import {
  getContentHeight,
  getScreenHeight,
  getScreenSize,
  getScreenWidth,
  getViewportHeight,
  isSmallScreen,
} from '../utils/screen'

export function useScreen() {
  const screenInfo = ref(getScreenInfo())

  // 响应式更新屏幕信息
  const updateScreenInfo = () => {
    screenInfo.value = getScreenInfo()
  }

  // 计算属性
  const contentHeight = computed(() => getContentHeight())
  const viewportHeight = computed(() => getViewportHeight())
  const screenWidth = computed(() => getScreenWidth())
  const screenHeight = computed(() => getScreenHeight())
  const screenSize = computed(() => getScreenSize())
  const isSmall = computed(() => isSmallScreen())

  // 监听屏幕变化
  onMounted(() => {
    // H5环境下监听窗口大小变化
    // #ifdef H5
    window.addEventListener('resize', updateScreenInfo)
    // #endif
  })

  onUnmounted(() => {
    // #ifdef H5
    window.removeEventListener('resize', updateScreenInfo)
    // #endif
  })

  return {
    screenInfo,
    contentHeight,
    viewportHeight,
    screenWidth,
    screenHeight,
    screenSize,
    isSmall,
    updateScreenInfo,
  }
}
